Checking whether the user input is a str in Python [migrated]

Posted by Sahil Babbar on Programmers See other posts from Programmers or by Sahil Babbar
Published on 2014-05-27T13:16:12Z Indexed on 2014/05/27 15:57 UTC
Read the original article Hit count: 258

Filed under:

I checked various questions on Stack Overflow but one thing every logic lacks. Let me demonstrate using Python:

while True:
    user_input = raw_input()
    if type(user_input) == str:
        print 'ERROR'
    else:
        print 'BINGO'

Also, we cannot use input() in place of raw_input() as it gives the error:Traceback (most recent call last):

File ".\test.py", line 3, in <module>
    user_input = int(input())
  File "<string>", line 1, in <module>
NameError: name 'asdf' is not defined

The problem here is that raw_input converts the user input into string so it always prints 'ERROR' and if I change the second line to

user_input = int(raw_input)

then, it gives an error:

Traceback (most recent call last):
  File ".\test.py", line 3, in <module>
    user_input = int(raw_input())
ValueError: invalid literal for int() with base 10: 'asdf'

I tried this with try and except but it shall work fine to check integer but not a string. I feel that this question may be marked as a duplicate but I think that this query is important, if logically taken.

© Programmers or respective owner

Related posts about python